<html>
<head>
    <title>哈里副屏 - 优化版</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #000;
            overflow: hidden;
            font-family: Arial, sans-serif;
        }
        #fps {
            position: absolute;
            left: 10px;
            top: 10px;
            color: lime;
            background: rgba(0,0,0,0.7);
            padding: 5px 10px;
            border-radius: 3px;
            z-index: 1000;
            font-weight: bold;
        }
        #latency {
            position: absolute;
            left: 10px;
            top: 50px;
            color: cyan;
            background: rgba(0,0,0,0.7);
            padding: 5px 10px;
            border-radius: 3px;
            z-index: 1000;
        }
        #status {
            position: absolute;
            right: 10px;
            top: 10px;
            color: white;
            background: rgba(0,0,0,0.7);
            padding: 5px 10px;
            border-radius: 3px;
            z-index: 1000;
        }
        #display {
            width: 100%;
            height: 100vh;
            object-fit: contain;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="fps">FPS: --</div>
    <div id="latency">延迟: -- ms</div>
    <div id="status">连接中...</div>
    <img id="display" onclick="FullScreen()" />

    <script>
        var ws = null;
        var imgElement = document.getElementById('display');
        var statusElement = document.getElementById('status');
        var fpsElement = document.getElementById('fps');
        var latencyElement = document.getElementById('latency');

        // 准确的FPS计算
        var frameTimes = [];
        var lastFrameTime = 0;
        var currentFps = 0;

        // 延迟测量
        var frameSendTime = 0;
        var averageLatency = 0;
        var latencySamples = [];

        // 渲染控制
        var targetFps = 30;
        var frameInterval = 1000 / targetFps;
        var lastRenderTime = 0;
        var framesDropped = 0;

        // 重新连接配置
        var reconnectAttempts = 0;
        var maxReconnectAttempts = 10;
        var reconnectDelay = 1000;

        connectWebSocket();

        function connectWebSocket() {
            try {
                statusElement.textContent = '连接中...';
                ws = new WebSocket('ws://' + window.location.host + '/display');

                ws.binaryType = 'arraybuffer';

                ws.onopen = function() {
                    statusElement.textContent = '已连接';
                    reconnectAttempts = 0;
                    console.log('WebSocket 连接成功');
                    // 开始渲染循环
                    requestAnimationFrame(renderLoop);
                };

                ws.onmessage = function(evt) {
                    var receiveTime = performance.now();
                    var latency = receiveTime - frameSendTime;

                    // 计算平均延迟
                    latencySamples.push(latency);
                    if (latencySamples.length > 10) {
                        latencySamples.shift();
                    }
                    averageLatency = latencySamples.reduce((a, b) => a + b) / latencySamples.length;

                    // 创建Blob URL
                    var blob = new Blob([evt.data], { type: 'image/jpeg' });
                    var url = URL.createObjectURL(blob);

                    // 预加载图像
                    var tempImg = new Image();
                    tempImg.onload = function() {
                        // 图像加载完成后，在渲染循环中显示
                        if (window.currentFrame) {
                            URL.revokeObjectURL(window.currentFrame.url);
                        }
                        window.currentFrame = {
                            img: tempImg,
                            url: url,
                            receiveTime: receiveTime
                        };
                    };
                    tempImg.src = url;

                    // 立即请求下一帧
                    if (ws.readyState === WebSocket.OPEN) {
                        frameSendTime = performance.now();
                        ws.send('next');
                    }
                };

                ws.onerror = function(error) {
                    console.error('WebSocket 错误:', error);
                    statusElement.textContent = '连接错误';
                };

                ws.onclose = function() {
                    statusElement.textContent = '连接断开';
                    console.log('WebSocket 连接关闭');
                    scheduleReconnect();
                };

            } catch (error) {
                console.error('连接失败:', error);
                scheduleReconnect();
            }
        }

        function renderLoop(timestamp) {
            // 控制帧率
            if (timestamp - lastRenderTime >= frameInterval) {
                // 更新显示的图像
                if (window.currentFrame) {
                    imgElement.src = window.currentFrame.img.src;

                    // 计算实际FPS
                    if (lastFrameTime > 0) {
                        var frameTime = timestamp - lastFrameTime;
                        frameTimes.push(frameTime);

                        if (frameTimes.length > 10) {
                            frameTimes.shift();
                        }

                        var averageFrameTime = frameTimes.reduce((a, b) => a + b) / frameTimes.length;
                        currentFps = 1000 / averageFrameTime;

                        // 更新显示
                        fpsElement.textContent = 'FPS: ' + Math.round(currentFps);
                        latencyElement.textContent = '延迟: ' + Math.round(averageLatency) + ' ms';
                    }

                    lastFrameTime = timestamp;
                }

                lastRenderTime = timestamp;
            }

            // 如果帧率过低，跳帧
            if (timestamp - lastRenderTime > frameInterval * 2) {
                framesDropped++;
                if (framesDropped % 10 === 0) {
                    console.log('跳帧次数:', framesDropped);
                }
                lastRenderTime = timestamp;
            }

            requestAnimationFrame(renderLoop);
        }

        function scheduleReconnect() {
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                var delay = reconnectDelay * Math.min(reconnectAttempts, 5);
                statusElement.textContent = `重连中... (${reconnectAttempts}/${maxReconnectAttempts})`;

                setTimeout(connectWebSocket, delay);
            } else {
                statusElement.textContent = '连接失败，请刷新页面';
            }
        }

        var is_full = false;
        function FullScreen() {
            if (!is_full) {
                if (imgElement.requestFullscreen) {
                    imgElement.requestFullscreen();
                } else if (imgElement.webkitRequestFullscreen) {
                    imgElement.webkitRequestFullscreen();
                } else if (imgElement.msRequestFullscreen) {
                    imgElement.msRequestFullscreen();
                }
                is_full = true;
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
                is_full = false;
            }
        }

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.close();
                }
            } else {
                connectWebSocket();
            }
        });
    </script>
</body>
</html>